<script lang="ts">
export default {
  name: 'YongHuGuanLiKKKK'
}
</script>
<script setup lang="ts">
import { ref } from 'vue'
import { Plus, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, type ComponentSize, type TabsPaneContext } from 'element-plus'
import { getJueSeWeiHuApi, addJueSeApi } from '@/api/system'
import { onMounted } from 'vue'
import { usetreeStore } from '@/stores/index'
// import { getTreeApi } from '@/api/system'
import { empowerArry, userStatus } from '../dictionary'
import addYongHu from './components/addYongHu.vue'

// 用户管理
const store = usetreeStore()
const activeName = ref('YongHu')
const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event)
}

// 删除用户
const deleteYongHuBtn = (row: any) => {
  delete row.password
  const params = {
    sqlId: JSON.stringify(['userMgr.deleteUser', 'userMgr.deleteUserRole']),
    sqlParam: JSON.stringify([[row], [row]]),
    dbName: undefined
  }
  ElMessageBox.confirm('你确定要删除该用户？', '删除用户', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await addJueSeApi(params)
        .then((res: any) => {
          if (res === 'success') {
            getYongHuData()
            ElMessage({ message: '删除成功', type: 'success' })
          } else {
            ElMessage({ message: '删除失败', type: 'error' })
          }
        })
        .catch(() => {
          ElMessage({ message: '删除失败', type: 'error' })
        })
    })
    .catch(() => {
      ElMessage({ message: '已取消删除', type: 'info' })
    })
}
// 用户维护 ----------------------------------------------------------------------
const YongHuloading = ref(true)
const YongHuTableData = ref<any>([])
const YongHuParams = ref<any>({
  userName: '',
  page: 1,
  rows: 20
})
const YongHuTotal = ref(0)
const YongHuSize = ref<ComponentSize>('default')

// 获取用户数据
const getYongHuData = async () => {
  YongHuloading.value = true
  const params = {
    sqlId: 'userMgr.getUserInfo',
    sqlParam: JSON.stringify({ userName: YongHuParams.value.userName }),
    pagination: true,
    page: YongHuParams.value.page,
    rows: YongHuParams.value.rows
  }
  await getJueSeWeiHuApi(params)
    .then((res: any) => {
      YongHuTotal.value = res.total
      YongHuTableData.value = res.rows.map((item: any) => {
        return {
          ...item,
          password: '******'
        }
      })
      YongHuloading.value = false
    })
    .catch(() => {
      ElMessage({ message: '请求失败', type: 'error' })
    })
}

// 添加角色
// 添加角色弹窗
const addChangeShow = ref(false)
const rowInfo = ref()
const acTitle = ref('添加角色')
const addYongHuBtn = () => {
  rowInfo.value = {}
  acTitle.value = '添加角色'
  addChangeShow.value = true
}
// 修改角色
const changeBtn = (row: any) => {
  acTitle.value = '修改角色'
  rowInfo.value = row
  addChangeShow.value = true
}
// 搜索角色
const YongHuSearchBtn = () => {
  getYongHuData()
}

// 角色授权 ----------------------------------------------------------------------
const JueSeloading = ref(true)
const JueSeFrom = ref({
  userId: '',
  roleName: '',
  roleFlag: -1,
  page: 1,
  rows: 20
})
const JueSeOptions = empowerArry
const JueSeTableData = ref<any>([])
const JueSeTotal = ref(0)
const JueSeSize = ref<ComponentSize>('default')
const multipleTableRef = ref<any>() // 表格ref
const authorizedArry = ref<any>([]) // 授权数组
// 获取角色数据
const getJueSeData = async () => {
  JueSeloading.value = true
  JueSeTableData.value = []
  multipleSelection.value = []
  authorizedArry.value = []
  multipleTableRef.value.clearSelection()
  const params = {
    sqlId: 'userMgr.getUserRole',
    sqlParam: JSON.stringify({
      userId: JueSeFrom.value.userId,
      roleName: JueSeFrom.value.roleName,
      roleFlag: JueSeFrom.value.roleFlag
    }),
    pagination: true,
    page: JueSeFrom.value.page,
    rows: JueSeFrom.value.rows
  }
  await getJueSeWeiHuApi(params)
    .then((res: any) => {
      JueSeTotal.value = res.total
      JueSeTableData.value = res.rows
      JueSeTableData.value.forEach((item: any) => {
        if (item.checked === 1) {
          authorizedArry.value.push({
            user_id: JueSeFrom.value.userId,
            role_id: item.role_id
          })
          multipleTableRef.value.toggleRowSelection(item, true)
        }
      })
      JueSeloading.value = false
    })
    .catch(() => {
      ElMessage({ message: '请求失败', type: 'error' })
    })
}
const JueSeClick = (row: any) => {
  activeName.value = 'JueSe'
  JueSeFrom.value.userId = row.user_id
  getJueSeData()
}

// 搜索角色
const JueSeSearchBtn = () => {
  getJueSeData()
}

const multipleSelection = ref<any[]>([])
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}

// 授权
const empowerFn = async () => {
  let addsqlParam = []
  let delsqlParam = []
  let sqlIdInfo = []
  let sqlParamInfo = []
  const sqlParam = multipleSelection.value.map((item: any) => {
    return {
      user_id: JueSeFrom.value.userId,
      role_id: item.role_id
    }
  })
  addsqlParam = sqlParam.filter(
    (sqlItem: any) =>
      !authorizedArry.value.some(
        (authorizedItem: any) => authorizedItem.role_id === sqlItem.role_id
      )
  )
  delsqlParam = authorizedArry.value.filter(
    (authorizedItem: any) =>
      !sqlParam.some((sqlItem: any) => sqlItem.role_id === authorizedItem.role_id)
  )
  // console.log(addsqlParam, delsqlParam)
  if (delsqlParam.length === 0 && addsqlParam.length === 0) {
    ElMessage({ message: '请选择角色', type: 'error' })
    return
  }
  if (delsqlParam.length > 0) {
    sqlIdInfo.push('userMgr.deleteUserRole')
    sqlParamInfo.push(delsqlParam)
  }
  if (addsqlParam.length > 0) {
    sqlIdInfo.push('userMgr.insertUserRole')
    sqlParamInfo.push(addsqlParam)
  }
  const params = {
    sqlId: JSON.stringify(sqlIdInfo), // userMgr.deleteUserRole
    sqlParam: JSON.stringify(sqlParamInfo)
  }
  // console.log(params)

  await addJueSeApi(params)
    .then((res: any) => {
      if (res === 'success') {
        getJueSeData()
        ElMessage({ message: '授权成功', type: 'success' })
      } else {
        ElMessage({ message: '授权失败', type: 'error' })
      }
    })
    .catch(() => {
      ElMessage({ message: '授权失败', type: 'error' })
    })
}
const empowerBtn = () => {
  empowerFn()
}

const handleSizeChange = (val: number) => {
  if (activeName.value === 'YongHu') {
    YongHuParams.value.page = 1
    YongHuParams.value.rows = val
    getYongHuData()
  }
  if (activeName.value === 'JueSe') {
    JueSeFrom.value.page = 1
    JueSeFrom.value.rows = val
    getJueSeData()
  }
}
const handleCurrentChange = (val: number) => {
  if (activeName.value === 'YongHu') {
    YongHuParams.value.page = val
    getYongHuData()
  }
  if (activeName.value === 'JueSe') {
    JueSeFrom.value.page = val
    getJueSeData()
  }
}

onMounted(() => {
  store.getRegionTree()
  store.getHxTree()
  getYongHuData()
})
</script>
<template>
  <div class="YongHuGuanLiBox">
    <el-tabs v-model="activeName" type="card" class="YongHuTabs" @tab-click="handleClick">
      <el-tab-pane class="YongHuWeiHu" label="用户维护" name="YongHu">
        <div id="actionBox">
          <el-form :inline="true" :model="YongHuParams" class="demo-form-inline">
            <el-form-item label="用户名：">
              <el-input v-model="YongHuParams.userName" placeholder="请输入用户名" clearable />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="Search" @click="YongHuSearchBtn">查询</el-button>
              <el-button type="success" plain :icon="Plus" @click="addYongHuBtn">添加</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-table
          v-loading="YongHuloading"
          class="YongHuWeiHuTable"
          :data="YongHuTableData"
          stripe
          border
          style="width: 100%"
        >
          <el-table-column prop="user_id" label="用户ID" width="130" />
          <el-table-column prop="user_name" label="用户名" width="140" />
          <el-table-column prop="password" label="密码" width="130" />
          <el-table-column prop="region_name" label="地域名称" width="180" />
          <el-table-column prop="hx_name" label="划小名称" width="200" />
          <el-table-column prop="telephone" label="手机号" width="120" />
          <el-table-column prop="email" label="邮箱" />
          <el-table-column prop="state" label="状态" width="80">
            <template #default="scope">
              <span>{{
                userStatus.filter((item) => item.value === Number(scope.row.state))[0].label
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="授权" width="180">
            <template #default="scope">
              <el-button text type="primary" @click="JueSeClick(scope.row)"> 角色授权 </el-button>
              <el-button type="warning" text @click="changeBtn(scope.row)">修改</el-button>
              <el-button type="danger" text @click="deleteYongHuBtn(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          class="paginationBox"
          v-model:current-page="YongHuParams.page"
          v-model:page-size="YongHuParams.rows"
          :page-sizes="[10, 20, 30, 40]"
          :size="YongHuSize"
          :disabled="false"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="YongHuTotal"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </el-tab-pane>
      <el-tab-pane
        class="JueSeShouQuan"
        label="角色授权"
        :disabled="activeName !== 'JueSe'"
        name="JueSe"
      >
        <!-- 1E1F22 -->
        <div id="actionBox">
          <el-form :inline="true" :model="JueSeFrom" class="demo-form-inline">
            <el-form-item label="角色名：">
              <el-input v-model="JueSeFrom.roleName" placeholder="请输入角色名" clearable />
            </el-form-item>
            <el-form-item label="授权类型：">
              <el-select
                v-model="JueSeFrom.roleFlag"
                placeholder="请选择授权类型"
                style="width: 120px"
              >
                <el-option
                  v-for="item in JueSeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" :icon="Search" @click="JueSeSearchBtn">查询</el-button>
              <el-button type="success" plain :icon="Plus" @click="empowerBtn">添加授权</el-button>
              <!-- <el-button type="danger" plain :icon="Minus" @click="cancelEmpowerBtn">取消授权</el-button> -->
            </el-form-item>
          </el-form>
        </div>
        <!-- @select="selectChange" @select-all="selectAllChange" -->
        <el-table
          v-loading="JueSeloading"
          ref="multipleTableRef"
          class="JueSeShouQuanTable"
          :data="JueSeTableData"
          stripe
          border
          :row-key="(row: any) => row.role_id"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" :reserve-selection="true" label="授权" width="40" />
          <el-table-column prop="role_id" label="角色ID" width="140" />
          <el-table-column prop="role_name" label="角色名" width="240" />
          <el-table-column prop="remark" label="备注" />
        </el-table>
        <el-pagination
          class="paginationBox"
          v-model:current-page="YongHuParams.page"
          v-model:page-size="YongHuParams.rows"
          :page-sizes="[10, 20, 30, 40]"
          :size="JueSeSize"
          :disabled="false"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="JueSeTotal"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </el-tab-pane>
    </el-tabs>
  </div>
  <addYongHu
    v-if="addChangeShow"
    v-model:is-show="addChangeShow"
    :title="acTitle"
    :form-info="rowInfo"
    @getYongHuData="getYongHuData"
  />
</template>
<style scoped lang="less">
#actionBox {
  padding: 0 8px;
  // margin-bottom: 15px;
  .el-button {
    padding: 0 16px;
  }
}

.YongHuGuanLiBox {
  position: relative;
  // padding-top: 4px;
  height: calc(100vh - 200px);
  .YongHuWeiHu {
    padding: 0 8px;
    .el-button {
      padding: 0;
    }
  }
  .YongHuWeiHuTable,
  .JueSeShouQuanTable {
    height: var(--tableBox-height);
  }
  .paginationBox {
    position: fixed;
    bottom: 20px;
  }

  .JueSeShouQuan {
    padding: 0 8px;
  }
  :deep(.el-tabs__header) {
    .el-tabs__nav {
      border-top: unset;
      border-left: unset;
      border-radius: 0;
    }
  }
}

// :deep(.JueSeShouQuanTable) {
//   padding: 0 8px;
//   .el-scrollbar__view {
//     width: 100%;
//     overflow: hidden;
//     .el-table__body {
//       width: 100% !important;
//     }
//   }
//   .el-button {
//     padding: 0;
//   }
// }
</style>
